package ar.com.duam.porky.movil.tasks;

import static ar.com.duam.porky.movil.ConstantesPorky.ENCODING_ISO_8859_1;
import static ar.com.duam.porky.movil.ConstantesPorky.URL_PORKY;
import static ar.com.duam.porky.movil.ConstantesPorky.WS_FIELD_SEPARATOR;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.util.Log;
import ar.com.duam.porky.movil.Concepto;
import ar.com.duam.porky.movil.Usuario;

public class DownloadConceptosTask extends AsyncTask<Usuario, Integer, List<Concepto>> 
{

	@Override
	protected List<Concepto> doInBackground(Usuario... params) 
	{
		Usuario usuario = params[0];
		List<Concepto> conceptos = new ArrayList<Concepto>();
		HttpURLConnection urlConnection = null;
		
		try 
		{
			URL url = new URL(URL_PORKY +"/ws/conceptos?username="+ usuario.getNombreUsuario());			
			urlConnection = (HttpURLConnection) url.openConnection();

			BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), ENCODING_ISO_8859_1));
			int size = urlConnection.getContentLength();
			Log.d(DownloadConceptosTask.class.getName(), "content-length: "+ size);
			
			int proccesed = 0;
			String line;
			
			while ((line = br.readLine()) != null)
			{
				String[] valores = line.split(WS_FIELD_SEPARATOR.replaceAll("\\|", "\\\\|"));
				conceptos.add(new Concepto(Integer.valueOf(valores[0]), usuario.getId(), valores[1], 0));
				
				proccesed += line.getBytes().length;
				publishProgress(proccesed / size * 100);
				
				Log.d(DownloadConceptosTask.class.getName(), "size: " + line.getBytes().length);
			}
		}
		catch (Exception ex)
		{
			Log.e("syncro", "Error descargando conceptos", ex);
		}
		finally 
		{
			urlConnection.disconnect();
		}
		
		return conceptos;
	}

}
